<?php
/**
 * App用户通用类
 * Created by PhpStorm.
 * User: tsingStar
 * Date: 2018/1/19
 * Time: 8:50
 */

namespace app\app\controller;


use app\common\model\GetEnvironment;
use app\common\model\RongYun;
use app\common\model\SendSms;
use app\common\model\SixunOpera;
use app\common\model\User;
use think\Controller;
use think\Exception;
use think\Log;
use think\Request;

class Pub extends Controller
{
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        //        Log::error($_POST);

    }

    public function test()
    {

        //推送订单支付成功
        $shop_id = input('shop_id');
        $employee = new \app\common\model\Employee();
        $tokens = $employee->where('shop_id', $shop_id)->column('jiguangToken');
        $shopModel = new \app\common\model\Shop();
        $jiguangToken = $shopModel->where('id', $shop_id)->value('jiguangToken');
        $tokens[] = $jiguangToken;
        print_r($tokens);
        $res = pushMess('你有新的订单待处理', ['scence'=>'order'], ['registration_id'=>$tokens], 2);
        exit($res);
    }
    public function checkOk()
    {
        exit_json();
    }

    /**
     * 获取上线状态--针对IOS上架处理
     */
    public function getOnline()
    {
        exit_json(1, '请求成功', ['userid' => "3370", 'code' => '3']);
    }

    /**
     * 更改默认USER_ID
     */
    public function setDefaultUserId()
    {
        $user_id = input('old_user_id');
        $user_id1 = input('new_user_id');
        model('shopcart')->where('user_id', $user_id1)->delete();
        $res = model('shopcart')->save(['user_id' => $user_id1], ['user_id' => $user_id]);
//        if ($res) {
            exit_json(1, '操作成功');
//        } else {
//            exit_json(-1, '操作失败');
//        }
    }

    public function getVersion()
    {
        $version = input('version');
        if ($version == config('version')) {
            exit_json(-1, '当前版本为最新版本');
        } else {
            exit_json(1, '有新版本', ['url' => config('download_url'), 'version' => config('version')]);
        }
    }


    function getConnStatus()
    {
        $mssql = new SixunOpera();
        var_dump($mssql->testConn());

    }

    /**
     *
     * 会员登陆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function login()
    {

        $telephone = input('post.phone');
        $password = input('post.password');

        $jiguangToken = input('post.jiguangToken');
        $userModel = new User();
        $user = $userModel->where('phone', 'eq', $telephone)->find();
        if ($user) {
            if ($user['password'] != $password) {
                exit_json(-1, '密码错误');
            }
            if ($user['status'] != 0) {
                exit_json(-1, '当前用户不存在');
            }
            $env = new GetEnvironment();
            $env = $env->environment();
            $data = ['jiguangToken' => $jiguangToken, 'device' => $env];
            if (!$user['rongyunToken']) {
                $rongYun = new RongYun();
                $token = $rongYun->getToken('vip' . $user['id'], $user['username'] ?$user['username']: $user['phone'], config('default_img'));
                $data['rongyunToken'] = $token;
            }
            $userModel->isUpdate(true)->save($data, ['id' => $user['id']]);
            exit_json(1, '登陆成功', $userModel->getUserInfo($user));
        } else {
            exit_json(-1, '会员不存在');
        }
    }

    /**
     * 会员注册
     */
    function register()
    {
        $data = input('post.');
        if (!$data['password']) {
            exit_json(-1, '密码格式不正确');
        }
//        $smsModel = new SendSms($data['phone']);
//        $vres = $smsModel->checkVcode($data['code']);
//        if (!$vres) {
//            exit_json(-1, $smsModel->getError());
//        }
        $data['password'] = $data['password'];
        $u = model('user')->where('phone', $data['phone'])->find();
        if($u){
            exit_json(-1, '当前手机号已注册');
        }
        $userModel = new User();
        $userModel->allowField(true)->isUpdate(false)->save($data);
        $userid = $userModel->getLastInsID();
        if ($userid) {
            $jiguangToken = input('post.jiguangToken');
            $rongYun = new RongYun();
            $token = $rongYun->getToken('vip' . $userid, $data['phone'], config('default_img'));
            $userModel->save(['rongyunToken' => $token, 'jiguangToken' => $jiguangToken], ['id' => $userid]);
            //注册赠送优惠券
            model('UserCoupon')->giveRegisterCoupon($userid);
            $user = $userModel->find($userid);
            exit_json(1, '注册成功', $userModel->getUserInfo($user));
        } else {
            exit_json(-1, '注册失败');
        }
    }

    /**
     * 重置密码
     */
    function resetPassword()
    {
        $data = input('post.');
        if (!$data['phone'] || !$data['code'] || !$data['password']) {
            exit_json(-1, '参数错误');
        }
        $smsModel = new SendSms($data['phone']);
        $vres = $smsModel->checkVcode($data['code']);
        if (!$vres) {
            exit_json(-1, '验证码错误');
        }
        $userModel = new User();
        $res = $userModel->save(['password' => $data['password']], ['phone' => $data['phone']]);
        if ($res) {
            exit_json();
        } else {
            exit_json(-1, '重置密码失败');
        }
    }

    /**
     * 获取验证码
     */
    function getVcode()
    {
        //sendType  1 注册 2 忘记密码
        $telephone = input('telephone');
        $sendType = input('sendType');
        if (!test_tel($telephone)) {
            exit_json(-1, '手机号不合法');
        }
        $sendSms = new SendSms($telephone, config('netease.tempId'), $sendType);
//        $res = $sendSms->sendVcode();
        if (true) {
            exit_json();
        } else {
            exit_json(-1, $sendSms->getError());
        }
    }


    /**
     * 更改商品
     */
    function changeGoodsStatus()
    {
        //下架商品
        $shopid = $_GET['shopid'];
        $gno = $_GET['gno'];
        $price = $_GET['price'];
        $price = sprintf('%.2f', $price);
        $total = sprintf('%.2f', $_GET['total']);
        if (!$shopid || !$gno || !$price || !$total) {
            exit(json_encode(array(
                'code' => -1, 'msg' => '参数不全'
            )));
        }
        $shop = model('shop')->where('fendian', $shopid)->find();
        $shopid = $shop['id'];
        $good = model('goods')->where(['gno' => $gno, 'shop_id' => $shopid])->find();
        if (!$good) {
            exit_json(1);
        }
        if ($good['bulk_package'] == 1) {
            if ($total > 0) {
                $prop = model('goods_prop')->where(['good_id' => $good['id'], 'prop_price' => $total, 'num' => ['gt', 0]])->find();
                if ($prop['id'] > 0) {
                    $prop->setDec('num');
                }
            } else {
                $total1 = abs($total);
                $prop_active_price = round($total1 * $shop['discount'], 2);
                $weight = round($total1 / $price, 4) * 1000;
                model('goods_prop')->save(['good_id' => $good['id'], 'prop_name' => $weight, 'prop_price' => $total1, 'num' => 1, 'prop_active_price' => $prop_active_price]);
            }
            $count = round($total / $good['bcost'], 4);
//            $this->mysql->query($sql);
        } else {
            $count = intval($total / $price);
        }
        //捆绑商品更改子商品库存量
        if ($good['combine_sta'] == 1) {
            $item = $this->getChildGood($gno);
//            $gno = trim(iconv('GBK', 'UTF-8', $item['item_no']));
            $count = $count * $item['item_qty'];
        }
//        $sql = "update ".Mysite::$app->config['tablepre'].'goods set count=count-'.$count.' where gno="'.$gno.'" and shopid='.$shopid;
        model('goods')->where(['gno' => $gno, 'shop_id' => $shopid])->setDec('count', $count);
        $g = model('goods')->where('id', $good['id'])->find();
        if($g['bulk_package'] == 1){
            $num = model('goods_prop')->where('good_id', $good['id'])->where('num', 'gt', 0)->count();
            if($num<=0){
                $good->save(['is_live'=>0]);
            }
        }else{
            if($g['count']<=0){
                $good->save(['is_live'=>0]);
            }
        }
//        $this->mysql->query($sql);

        exit(json_encode(array(
            'code' => 1
        )));
    }

    /**
     * 根据商品货号获取捆绑子商品信息
     * @param $combineNo
     * @return array
     */
    function getChildGood($combineNo)
    {
        $sixun = new SixunOpera();
        $good = $sixun->getChildGood($combineNo);
        return $good;
    }

    public function asyncUser()
    {
        $data = file_get_contents(__PUBLIC__ . '/a.json');
        $d = json_decode($data, true);
        echo count($d['RECORDS']);
        exit;
        model('user')->saveAll($d['RECORDS']);

    }

    /**
     * 获取广告位
     */
    public function getAdv()
    {
        $adv = model('AdvIndex')->order('create_time desc')->find();
        if(!$adv){
            exit_json(-1, '无广告');
        }
        if($adv['is_out'] == 0){
            $out_url = __URL__.'/index/Index/adv/adv_id/'.$adv['id'];
        }else{
            $out_url = $adv['out_url'];
        }
        exit_json(1, '请求成功', [
            'url'=>$out_url,
            'image'=>__URL__.$adv['image'],
            'time'=>$adv['time']
        ]);
    }


}